package com.jingpin.at.jingpin0527.service.impl;

import com.jingpin.at.jingpin0527.Oa;
import com.jingpin.at.jingpin0527.dao.OaMapper;
import com.jingpin.at.jingpin0527.service.OaService;
import lombok.extern.log4j.Log4j;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Service(value = "oaService")
@Log4j
public class OaServiceImpl implements OaService {

    @Resource
    private OaMapper oaMapper;

    @Override
    public void getOa() {
        List<Oa> oas = oaMapper.getOa();
        for (int i = 0; i < oas.size(); i++) {
            WxArticle wxArt = new WxArticle("/Users/jing_pin/Desktop/juzi/" + oas.get(i).getOaName().replace(" ", ""));
            wxArt.setBaseUrl(oas.get(i).getOa());
            //调用单线程下载方法
            //wxArt.spiderImgsDownLoad();
            //调用多线程下载方法
            wxArt.spiderImgsByMultipleThreadsDownLoad(oas.get(i).getOaName().replace("", ""));
            //关闭线程池
            wxArt.shutDown();
        }
    }

    private static final Logger logger = LoggerFactory.getLogger(OaServiceImpl.class);
    private static final String HTTP_URL = "http://mp.weixin.qq.com/s?__biz=MzI5NjIwNDM1OA==&amp;mid=2247519978&amp;" +
            "idx=1&amp;sn=1d13846cd59e7537bd6aa35f1147a66b&amp;" +
            "chksm=ec452fc3db32a6d59564dc4e9cc38f5ff90b9dfa9773c1d94ec34a2c80f4a7991b7b98af0378&amp;" +
            "scene=21#wechat_redirect";
    private static final String IMAGE_PATH = "/Users/jing_pin/Desktop/";
    private List<String> imageUrl = new ArrayList<String>();//用于存储图片的url
    private static int count = 0;//图片计数器

    //public static void main(String[] args) {
    //    String netUrl = "https://mp.weixin.qq.com/s?__biz=MzI5NjIwNDM1OA==&amp;mid=2247519978&amp;idx=1&amp;" +
    //            "sn=1d13846cd59e7537bd6aa35f1147a66b&amp;" +
    //            "chksm=ec452fc3db32a6d59564dc4e9cc38f5ff90b9dfa9773c1d94ec34a2c80f4a7991b7b98af0378&amp;scene=21";
    //    //要爬的网页
    //    new OaServiceImpl().init(netUrl);
    //}

    public void init(String netUrl) {
        getPage(netUrl);
        while (imageUrl.size() != 0) {
            getImage(imageUrl.remove(0));
        }
    }

    //获取网页信息line中的图片url并加入到集合中
    public void getImageUrl(String line) {
        String regex = "src=\"http://.{1,}.jpg";
        Pattern pat = Pattern.compile(regex);
        Matcher matcher = pat.matcher(line);
        String str = null;
        while (matcher.find()) {
            str = matcher.group();
            imageUrl.add(str.substring(5));
        }
    }

    //爬取网页中的信息。
    public void getPage(String netUrl) {
        BufferedReader mybr = null;
        try {
            URL myurl = new URL(netUrl);
            URLConnection myconn = myurl.openConnection();
            InputStream myin = myconn.getInputStream();
            mybr = new BufferedReader(new InputStreamReader(myin, "UTF-8"));
            String line;
            while ((line = mybr.readLine()) != null) {
                getImageUrl(line);//判断网页中的jpg图片
            }
        } catch (MalformedURLException e) {
            System.out.println("url异常");
        } catch (IOException e) {
            System.out.println("url连接异常");
        } finally {
            if (mybr != null) {
                try {
                    mybr.close();
                } catch (IOException e) {
                    System.out.println("读入流关闭异常");
                }
            }
        }
    }

    private static void downImages(String imgUrl) {
        File imgFilePath = new File(IMAGE_PATH);
        //如果目录不存在，创建目录
        if (!imgFilePath.exists()) {
            boolean mkdir = imgFilePath.mkdir();
            logger.info(mkdir ? "程序已自动创建目录" : "");
        }
        //拼接image下载地址
        String beforeUrl = imgUrl.substring(0, imgUrl.lastIndexOf("/") + 1);
        String imgName = imgUrl.substring(imgUrl.lastIndexOf("/") + 1);
        String newImgName = imgName;

        try {
            newImgName = URLEncoder.encode(imgName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("图片名称有误");
            e.printStackTrace();
        }
        imgUrl = beforeUrl + newImgName;
        try {
            //获取下载地址
            URL url = new URL(imgUrl);
            InputStream in = null;
            OutputStream out = null;
            try {
                //链接网络地址，创建连接对象
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                //建立到远程对象的实际连接
                connection.connect();
                //连接成功
                if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    //获取链接的输入流
                    in = connection.getInputStream();
                    //创建下载到本地的文件
                    File imgFile = new File(IMAGE_PATH, imgName);
                    if (imgFile.exists()) {
                        logger.info(imgName + " 该图片已存在");
                    } else {
                        //写入文件
                        out = new FileOutputStream(imgFile);
                        byte[] buf = new byte[1024];
                        int len;
                        while ((len = in.read(buf)) != -1) {
                            out.write(buf, 0, len);
                        }
                        out.flush();
                        //断开连接
                        connection.disconnect();
                        logger.info(imgName + "下载成功");
                    }
                } else {
                    logger.warn("连接失败");
                }

            } catch (IOException e) {
                logger.error("下载图片失败");
                e.printStackTrace();
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }

                    if (in != null) {
                        in.close();
                    }
                } catch (IOException e) {
                    logger.error("读写流关闭出现异常");
                    e.printStackTrace();
                }
            }
        } catch (MalformedURLException e) {
            logger.error("网址格式错误");
            e.printStackTrace();
        }
    }

    public static void getImage(String imageUrl) {
        InputStream myin = null;
        BufferedOutputStream myos = null;
        try {
            URL myurl = new URL(imageUrl);
            URLConnection myconn = myurl.openConnection();
            myin = myconn.getInputStream();
            myos = new BufferedOutputStream(new FileOutputStream(count + ".jpg"));
            byte[] buff = new byte[1024];
            int num = 0;
            while ((num = myin.read(buff)) != -1) {
                myos.write(buff, 0, num);
                myos.flush();
            }
            count++;
        } catch (MalformedURLException e) {
            System.out.println("url异常");
        } catch (IOException e) {
            System.out.println("url连接异常");
        } finally {
            if (myin != null) {
                try {
                    myos.close();
                } catch (IOException e) {
                    System.out.println("读入流关闭异常");
                }
            }
            if (myos != null) {
                try {
                    myos.close();
                } catch (IOException e) {
                    System.out.println("输出流关闭异常");
                }
            }
        }
    }

    public static void main(String[] args) {
        BigDecimal bigDecimal = new BigDecimal(0.00);
        System.out.println(bigDecimal.compareTo(null));
    }
}
